﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace RecruitmentProcess
{
    public sealed partial class RecruitmentWorkflow : StateMachineWorkflowActivity
    {
        int totTask = 4;
        int currentTask = 0;

        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

        public Guid createTaskInitialClearanceTaskId = default(System.Guid);
        public SPWorkflowTaskProperties createTaskInitialClearanceTaskProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedInitialClearanceBeforeProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedInitialClearanceAfterProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();

        public Guid createTaskTechnicalClearanceTaskId = default(System.Guid);
        public SPWorkflowTaskProperties createTaskTechnicalClearanceTaskProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedTechnicalClearanceAfterProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedTechnicalClearanceBeforeProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();

        public Guid createTaskHRClearanceTaskId = default(System.Guid);
        public SPWorkflowTaskProperties createTaskHRClearanceTaskProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedHRClearanceAfterProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedHRClearanceBeforeProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();

        public Guid createTaskAcceptedTaskId = default(System.Guid);
        public SPWorkflowTaskProperties createTaskAcceptedTaskProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedAcceptedAfterProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedAcceptedBeforeProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();

        public Guid createTaskRejectedTaskId = default(System.Guid);
        public SPWorkflowTaskProperties createTaskRejectedTaskProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedRejectedAfterProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChangedRejectedBeforeProperties = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();

        public RecruitmentWorkflow()
        {
            InitializeComponent();
        }

        #region Workflow Activated
        private void onWorkflowActivatedInitial_Invoked(object sender, ExternalDataEventArgs e)
        {

        }
        #endregion Workflow Activated

        #region Initial Clearance
        private void createTaskInitialClearance_MethodInvoking(object sender, EventArgs e)
        {
            try
            {
                //Create a new TaskId for the Task
                this.createTaskInitialClearanceTaskId = Guid.NewGuid();

                //TaskProperties field is used to configure the Task Details.
                this.createTaskInitialClearanceTaskProperties.Title = "Initial Clearance";
                //You can assign a Task to an user or to a group. Here we assign the task to HR-Group
                this.createTaskInitialClearanceTaskProperties.AssignedTo = "HRGroup";

                //Task Type corresponds to TaskURN specified in Elements.xml
                this.createTaskInitialClearanceTaskProperties.TaskType = 1;

                this.createTaskInitialClearanceTaskProperties.DueDate = DateTime.Today.AddDays(5.0);
            }
            catch (Exception ex)
            {
                //Logging is used so that we can debug the errors in the workflow.
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
            }
        }

        private void onTaskChangedInitialClearance_Invoked(object sender, ExternalDataEventArgs e)
        {
            try
            {
                this.onTaskChangedInitialClearanceAfterProperties = this.onTaskChangedInitialClearance.AfterProperties;
                this.onTaskChangedInitialClearanceBeforeProperties = this.onTaskChangedInitialClearance.BeforeProperties;

                //Set the PercentComplete property to 1.0 (i.e. 100%) to indicate that the task has been completed.
                this.onTaskChangedInitialClearanceAfterProperties.PercentComplete = (float)1.0;

                //Get the value of Remarks Column (InfoPath Form) by using the ExtendedProperties property
                string remarks = this.onTaskChangedInitialClearanceBeforeProperties.ExtendedProperties["Comment"].ToString();

                SPListItem listItem = this.workflowProperties.Item;

                //Write the remarks value to the list item
                if (listItem != null && listItem.Fields.ContainsField("InitialRemarks"))
                {
                    listItem["InitialRemarks"] = remarks;
                }
                if (this.onTaskChangedInitialClearanceAfterProperties.PercentComplete == (float)1.0 && this.onTaskChangedInitialClearanceAfterProperties.ExtendedProperties["ApprovalStatus"].ToString().Contains("Accept"))
                {
                    this.TaskOutcomeStatus = "Approved";
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
                //throw ex;
            }
        }

        private void InitialClearanceApprovalProcess(object sender, ConditionalEventArgs e)
        {
            try
            {
                if (this.onTaskChangedInitialClearanceAfterProperties.PercentComplete == (float)1.0 && this.onTaskChangedInitialClearanceAfterProperties.ExtendedProperties["ApprovalStatus"].ToString().Contains("Accept"))
                {
                    e.Result = true;
                }
                else
                {
                    e.Result = false;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
            }
        }
        #endregion Initial Clearance

        #region Technical Clearance
        private void createTaskTechnicalClearance_MethodInvoking(object sender, EventArgs e)
        {
            try
            {
                //Create a new TaskId for the Task
                this.createTaskTechnicalClearanceTaskId = Guid.NewGuid();

                //TaskProperties field is used to configure the Task Details.
                this.createTaskTechnicalClearanceTaskProperties.Title = "Technical Clearance";

                //You can assign a Task to an user or to a group. Here we assign the task to HR-Group

                SPListItem listItem = this.workflowProperties.Item;
                //Write the remarks value to the list item
                if (listItem != null)
                {
                    //Check if TechnicalInterviewAssignedTo Field has a value, and Assign this Task to the value of this Field
                    if (listItem.Fields.ContainsField("TechnicalInterviewAssignedTo"))
                    {
                        this.createTaskTechnicalClearanceTaskProperties.AssignedTo = listItem["TechnicalInterviewAssignedTo"].ToString();
                    }

                    //To send InitialRemarks to the InfoPath Form, we add it to the ExtendedProperty of the TaskProperties
                    //ExtendedProperties is a hashtable (Key-Value pair). 
                    //The Key will be the name of field we have used in ItemMetaData.xml and Value will be the value of remarks
                    if (listItem.Fields.ContainsField("InitialRemarks"))
                    {
                        if (this.createTaskTechnicalClearanceTaskProperties.ExtendedProperties.ContainsKey("InitialComments"))
                        {
                            this.createTaskTechnicalClearanceTaskProperties.ExtendedProperties["InitialComments"] = listItem["InitialRemarks"].ToString();
                        }
                        else
                        {
                            this.createTaskTechnicalClearanceTaskProperties.ExtendedProperties.Add("InitialComments", listItem["InitialRemarks"].ToString());
                        }
                    }
                }

                //Task Type corresponds to TaskURN specified in Elements.xml
                this.createTaskTechnicalClearanceTaskProperties.TaskType = 2;

                this.createTaskTechnicalClearanceTaskProperties.DueDate = DateTime.Today.AddDays(2.0);
            }
            catch (Exception ex)
            {
                //Logging is used so that we can debug the errors in the workflow.
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
            }
        }

        private void onTaskChangedTechnicalClearance_Invoked(object sender, ExternalDataEventArgs e)
        {
            try
            {
                this.onTaskChangedTechnicalClearanceAfterProperties = this.onTaskChangedTechnicalClearance.AfterProperties;
                this.onTaskChangedTechnicalClearanceBeforeProperties = this.onTaskChangedTechnicalClearance.BeforeProperties;

                //Set the PercentComplete property to 1.0 (i.e. 100%) to indicate that the task has been completed.
                this.onTaskChangedTechnicalClearanceAfterProperties.PercentComplete = (float)1.0;

                //Get the value of Remarks Column (InfoPath Form) by using the ExtendedProperties property
                string remarks = this.onTaskChangedTechnicalClearanceBeforeProperties.ExtendedProperties["FinalComment"].ToString();

                SPListItem listItem = this.workflowProperties.Item;

                //Write the remarks value to the list item
                if (listItem != null && listItem.Fields.ContainsField("TechnicalInterviewRemarks"))
                {
                    listItem["TechnicalInterviewRemarks"] = remarks;
                }

                if (this.onTaskChangedTechnicalClearanceAfterProperties.PercentComplete == (float)1.0 && this.onTaskChangedTechnicalClearanceAfterProperties.ExtendedProperties["Statu"].ToString().Contains("Approve"))
                {
                    this.TaskOutcomeStatus = "Approved";
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
                //throw ex;
            }
        }

        private void TechnicalClearanceApprovalProcess(object sender, ConditionalEventArgs e)
        {
            try
            {
                if (this.onTaskChangedTechnicalClearanceAfterProperties.PercentComplete == (float)1.0 && this.onTaskChangedTechnicalClearanceAfterProperties.ExtendedProperties["ApprovalStatus"].ToString().Contains("Accept"))
                {
                    e.Result = true;
                }
                else
                {
                    e.Result = false;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
            }
        }
        #endregion Technical Clearance

        #region HR Clearance
        private void createTaskHRClearance_MethodInvoking(object sender, EventArgs e)
        {
            try
            {
                //Create a new TaskId for the Task
                this.createTaskInitialClearanceTaskId = Guid.NewGuid();

                //TaskProperties field is used to configure the Task Details.
                this.createTaskInitialClearanceTaskProperties.Title = "Initial Clearance";
                //You can assign a Task to an user or to a group. Here we assign the task to HR-Group
                this.createTaskInitialClearanceTaskProperties.AssignedTo = "HRGroup";

                //Task Type corresponds to TaskURN specified in Elements.xml
                this.createTaskInitialClearanceTaskProperties.TaskType = 1;

                this.createTaskInitialClearanceTaskProperties.DueDate = DateTime.Today.AddDays(5.0);
            }
            catch (Exception ex)
            {
                //Logging is used so that we can debug the errors in the workflow.
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
            }
        }

        private void onTaskChangedHRClearance_Invoked(object sender, ExternalDataEventArgs e)
        {

        }

        private void HRClearanceApprovalProcess(object sender, ConditionalEventArgs e)
        {

        }
        #endregion HR Clearance

        #region Accepted
        private void createTaskAccepted_MethodInvoking(object sender, EventArgs e)
        {

        }

        private void onTaskChangedAccepted_Invoked(object sender, ExternalDataEventArgs e)
        {

        }
        #endregion Accepted

        #region Rejected
        private void createTaskRejected_MethodInvoking(object sender, EventArgs e)
        {
            try
            {
                this.currentTask++;
                //Create a new TaskId for the Task
                this.createTaskRejectedTaskId = Guid.NewGuid();

                //TaskProperties field is used to configure the Task Details.
                this.createTaskRejectedTaskProperties.Title = "Technical Rejected Clearance";

                //You can assign a Task to an user or to a group. Here we assign the task to HR-Group

                SPListItem listItem = this.workflowProperties.Item;
                //Write the remarks value to the list item
                if (listItem != null)
                {
                    //Check if TechnicalInterviewAssignedTo Field has a value, and Assign this Task to the value of this Field
                    if (listItem.Fields.ContainsField("TechnicalInterviewAssignedTo"))
                    {
                        this.createTaskRejectedTaskProperties.AssignedTo = listItem["TechnicalInterviewAssignedTo"].ToString();
                    }

                    //To send InitialRemarks to the InfoPath Form, we add it to the ExtendedProperty of the TaskProperties
                    //ExtendedProperties is a hashtable (Key-Value pair). 
                    //The Key will be the name of field we have used in ItemMetaData.xml and Value will be the value of remarks
                    if (listItem.Fields.ContainsField("InitialRemarks"))
                    {
                        if (this.createTaskRejectedTaskProperties.ExtendedProperties.ContainsKey("InitialComments"))
                        {
                            this.createTaskRejectedTaskProperties.ExtendedProperties["InitialComments"] = listItem["InitialRemarks"].ToString();
                        }
                        else
                        {
                            this.createTaskRejectedTaskProperties.ExtendedProperties.Add("InitialComments", listItem["InitialRemarks"].ToString());
                        }
                    }
                }

                //Task Type corresponds to TaskURN specified in Elements.xml
                this.createTaskRejectedTaskProperties.TaskType = 2;

                this.createTaskRejectedTaskProperties.DueDate = DateTime.Today.AddDays(2.0);
            }
            catch (Exception ex)
            {
                //Logging is used so that we can debug the errors in the workflow.
                System.Diagnostics.EventLog.WriteEntry("Recruitment Workflow", ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                LogToHistoryListActivity log = new LogToHistoryListActivity();
                log.HistoryDescription = ex.StackTrace;
            }

        }

        private void onTaskChangedRejected_Invoked(object sender, ExternalDataEventArgs e)
        {

        }
        #endregion Rejected

        public static DependencyProperty TaskOutcomeStatusProperty = DependencyProperty.Register("TaskOutcomeStatus", typeof(System.String), typeof(RecruitmentProcess.RecruitmentWorkflow));

        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [BrowsableAttribute(true)]
        [CategoryAttribute("Misc")]
        public String TaskOutcomeStatus
        {
            get
            {
                return ((string)(base.GetValue(RecruitmentProcess.RecruitmentWorkflow.TaskOutcomeStatusProperty)));
            }
            set
            {
                base.SetValue(RecruitmentProcess.RecruitmentWorkflow.TaskOutcomeStatusProperty, value);
            }
        }
    }
}
